const { secret } = require("./token");
const jwt = require("jsonwebtoken");

/*白名单，登录、刷新短token不受限制，也就不用token验证*/
const whiteList = ["/zhc/refresh",
    "/zhc/passwordLogin",
    "/zhc/faceLogin",
    "/zhc/getCode",
    "/zhc/phoneLogin",
    "/zhc/verifyCode",
    "/zhc/updatePsd",
    "/zhc/submit",
    ''];
const isWhiteList = (url, whiteList) => {

    return whiteList.find((item) => item === url) ? true : false;
};

/*
中间件
验证短token是否有效
*/
const auth = async (req, res, next) => {
    console.log(req.url);
    
    let url = req.url; //获取请求路径 /phonelogin
    if (isWhiteList(url, whiteList)||req.url.includes('/uploads')) {
        //执行下一步
        return await next();
    } else {
        //获取请求头携带的短token
        const a_tk = req.headers.accesstoken;
        if (!a_tk) {
            //判断短token是否存在，不存在返回401
            return res.send({
                code: 401,
                msg: "accessToken不存在",
            });
        } else {
            //短token存在 则解析token 判断短token是否有效
            await jwt.verify(a_tk, secret, async (err, data) => {
                if (err) {
                    //无效则返回
                    return res.send({
                        code: 401,
                        msg: "accessToken无效",
                    });
                } else {
                    //有效则执行下一步
                    return await next();
                }
            });
        }
    }
};

module.exports = {
    auth,
};
